//
//  SwiperCollectionView.swift
//  UserApp_iOS
//
//  Created by linlin on 2019/9/14.
//  Copyright © 2019 linlin. All rights reserved.
//

import UIKit
import Kingfisher

class SwiperNewView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var pageControl: UIPageControl?
    let cellIdentify = "swiperCell"
    var viewLayout: UICollectionViewFlowLayout!
    var collectView: UICollectionView!
    weak var timer: Timer?

    var numberOfItemsPerPage: Int = 1{
        didSet{
            if numberOfItemsPerPage > 1 {
                viewLayout.itemSize = CGSize(width: (width-CGFloat(10*(numberOfItemsPerPage-1)))/CGFloat(numberOfItemsPerPage), height: 65)
                viewLayout.minimumInteritemSpacing = 10
                pageControl?.isHidden = true
            }
        }
    }
    private var numberOfPage: Int = 1{
        didSet{
            pageControl?.currentPage = 0
            pageControl?.numberOfPages = numberOfPage
        }
    }
    var navigats: [AppNavigate]?{
        didSet{
            var images: [String] = []
            navigats?.forEach({ (nav: AppNavigate) in
                if nav.ImageUrl != nil {
                    
                    images.append(nav.ImageUrl!)
                }
            })
            if images.count > 0{
                imagesList = images
            }
        }
    }
    var imagesList: [String]?{
        didSet{
            if let images = imagesList {
                numberOfPage = images.count % numberOfItemsPerPage > 0 ? (images.count/numberOfItemsPerPage + 1) : images.count/numberOfItemsPerPage
                UIView.animate(withDuration: 0.0, animations: {[unowned self] in
                    self.collectView.reloadData()
                }) { (finished) in
                    self.stop()
                    self.start()
                }
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }

    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        setNeedsLayout()
        initViews()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if numberOfItemsPerPage == 1 {
            viewLayout.itemSize = CGSize(width: width, height: height)
        }
    }
    
    func initViews() -> Void{

        viewLayout = UICollectionViewFlowLayout()
        viewLayout.headerReferenceSize = .zero
        viewLayout.footerReferenceSize = .zero
        viewLayout.minimumLineSpacing = 0
        viewLayout.minimumInteritemSpacing = 0
        viewLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        viewLayout.scrollDirection = .horizontal
        viewLayout.itemSize = CGSize(width: width, height: height)

//
        collectView = UICollectionView(frame: self.bounds, collectionViewLayout: viewLayout)
        collectView.register(SwipperCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentify)
        
        collectView.bounces = false
        collectView.isPagingEnabled = true
        collectView.showsHorizontalScrollIndicator = false
        collectView.showsVerticalScrollIndicator = false
        collectView.dataSource = self
        collectView.delegate = self
        collectView.backgroundColor = .clear
        self.addSubview(collectView)
        
        initPageControl()
    }
    
    func initPageControl() -> Void {
        pageControl = UIPageControl(frame: CGRect(x: 0, y: height-40, width: width, height: 40))
        pageControl?.currentPage = 0
        pageControl?.numberOfPages = 0
        pageControl?.currentPageIndicatorTintColor = colorTheme
        pageControl?.pageIndicatorTintColor = .white
        pageControl?.hidesForSinglePage = true
        self.addSubview(pageControl!)
        self.bringSubviewToFront(pageControl!)
    }
    
    func start() -> Void {
        if numberOfItemsPerPage > 1 {
            pageControl?.isHidden = true
        }
        timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(changePage), userInfo: nil, repeats: true)
    }
    
    func stop() -> Void {
        timer?.invalidate()
    }
    
    @objc func changePage() -> Void{
        if let _ = imagesList{
            let currentPage: Int = (pageControl!.currentPage == (numberOfPage-1)) ? 0 : (pageControl!.currentPage + 1)
            let indexPath: IndexPath = IndexPath(item: currentPage*numberOfItemsPerPage, section: 0)
                collectView.scrollToItem(at: indexPath, at: .left, animated: true)
            pageControl?.currentPage = currentPage
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let images = imagesList {
            let num = images.count % numberOfItemsPerPage == 0 ? images.count : (images.count + images.count % numberOfItemsPerPage)
            return num
        }
        return 0
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentify, for: indexPath) as! SwipperCollectionViewCell
        if indexPath.item < imagesList?.count ?? 0 {
            let url = imagesList![indexPath.item]
            cell.logoImage.kf.setImage(with: ImageResource(downloadURL: URL(string: url)!))
        } else {
            cell.logoImage.image = nil
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        pageControl?.currentPage = indexPath.item/numberOfItemsPerPage
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item < imagesList?.count ?? 0 {
            let navigate = navigats?[indexPath.item]
            if let url = navigate?.LoctionUrl{
//                WebViewController.show(from: topViewController, webUrl: url)
            }
        }
    }
}
